package org.sardine.util;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class ClassUtils {
	
	private static final Map primitiveTypeNameMap = new HashMap(16);
	
	static{
		
		Set primitiveTypeNames = new HashSet(16);
		primitiveTypeNames.add(boolean.class);
		primitiveTypeNames.add(boolean[].class);
		primitiveTypeNames.add(byte.class);
		primitiveTypeNames.add(byte[].class);
		primitiveTypeNames.add(char.class);
		primitiveTypeNames.add(char[].class);
		primitiveTypeNames.add(double.class);
		primitiveTypeNames.add(double[].class);
		primitiveTypeNames.add(float.class);
		primitiveTypeNames.add(float[].class);
		primitiveTypeNames.add(int.class);
		primitiveTypeNames.add(int[].class);
		primitiveTypeNames.add(long.class);
		primitiveTypeNames.add(long[].class);
		primitiveTypeNames.add(short.class);
		primitiveTypeNames.add(short[].class);
		
		for (Iterator it = primitiveTypeNames.iterator(); it.hasNext();) {
			Class primitiveClass = (Class) it.next();
			primitiveTypeNameMap.put(primitiveClass.getName(), primitiveClass);
		}
		
	}
	
	public static ClassLoader getDefaultClassLoader(){
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		if(cl == null){
			cl = ClassUtils.class.getClassLoader();
		}
		return cl;
	}
	
	public static Class forName(String className) throws ClassNotFoundException{
		return forName(className,getDefaultClassLoader());
	}
	
	public static Class forName(String className, ClassLoader classLoader) throws ClassNotFoundException{
		
		if(classLoader == null){
			classLoader = getDefaultClassLoader();
		}
		
		Class clazz = (Class)primitiveTypeNameMap.get(className);
		if (clazz != null) {
			return clazz;
		}
		
		return classLoader.loadClass(className);
		
	}

}
